<?php

namespace app\api\controller;

use app\admin\model\DormitoryBuilding;
use app\admin\model\DormitoryDorm;
use app\admin\model\DormitoryDormBed;
use app\common\controller\Api;
use app\common\model\BehaviorRecord;
use EasyWeChat\Foundation\Application;
use think\File;


/**
 * 寝室接口
 */
class Dorm extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (查看寝室信息)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/8 15:05)
     * @ApiSummary  (两种获取方式 第一种:根据参数dorm_id直接获取 第二种:根据garden_number,building_number,dorm_number三个参数一起获取)
     * @ApiBody     (两种获取方式 第一种:根据参数dorm_id直接获取 第二种:根据garden_number,building_number,dorm_number三个参数一起获取)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/profile)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="dorm_id", type="string", required=false, description="寝室id", sample="")
     * @ApiParams   (name="garden_number", type="string", required=false, description="园区号", sample="")
     * @ApiParams   (name="building_number", type="string", required=false, description="楼栋号", sample="")
     * @ApiParams   (name="dorm_number", type="string", required=false, description="寝室号", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1565248066",
    "data": {
    "dorm": {
    "id": 884,
    "garden_number": "1",
    "garden_name": "雅园",
    "building_number": "1",
    "building_name": "1号楼",
    "number": "1-101"
    },
    "bed_list": [
    {
    "id": 4025,
    "num": 1,
    "student_id": 2
    }
    ]
    }
    })
     */
    public function profile()
    {
        $dorm_id = $this->request->post('dorm_id');

        if ($dorm_id) {
            $cond['a.id'] = $dorm_id;

        } else {

            $validate = new \think\Validate([
                'garden_number' => 'require',
                'building_number' => 'require',
                'dorm_number' => 'require'
            ], [], [
                'garden_number' => '园区号',
                'building_number' => '楼栋号',
                'dorm_number' => '寝室号',
            ]);

            if (!$validate->check($this->request->request())) {
                $this->error($validate->getError());
            }

            $cond['a.garden_number'] = $this->request->post('garden_number');
            $cond['a.building_number'] = $this->request->post('building_number');
            $cond['a.number'] = $this->request->post('dorm_number');

        }

        $dorm = DormitoryDorm::alias('a')
            ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number', 'left')
            ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number', 'left')
            ->where($cond)
            ->where('a.status', DormitoryDorm::NORMAL)
            ->field('a.id,a.garden_number,c.name as garden_name,a.building_number,d.name as building_name,a.number')
            ->find();

        if (!$dorm) $this->error('寝室不存在');

        $data['dorm'] = $dorm;
        $data['bed_list'] = DormitoryDormBed::where('garden_number', $dorm['garden_number'])
            ->where('building_number', $dorm['building_number'])
            ->where('dorm_number', $dorm['number'])
            ->where('status', DormitoryDormBed::ZAIYONG)
            ->where('student_id', '>', 0)
            ->field('id,num,student_id')
            ->order('num', 'asc')
            ->select();

        $this->success('', $data);

    }

    /**
     * @ApiTitle    (搜索寝室)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/8 15:37)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/search)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="keywords", type="string", required=false, description="寝室号或寝室名", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码 默认1", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function search()
    {
        $keywords = $this->request->post('keywords');

        $results = DormitoryDorm::alias('a')
            ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number')
            ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number')
            ->where('a.number|a.name', 'like', "%$keywords%")
            ->where('a.status', DormitoryDorm::NORMAL)
            ->field('a.id,a.garden_number,c.name as garden_name,a.building_number,d.name as building_name,a.number,a.bed_count,a.bed_used_count')
            ->paginate();

        $this->success('', $results);

    }

    /**
     * @ApiTitle    (寝室排行榜)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/12 11:00)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/ranking)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function ranking()
    {
        $list_rows = $this->request->request('list_rows', 10);

        $results = DormitoryDorm::alias('a')
            ->join('__DORMITORY_GARDEN__ c', 'c.number = a.garden_number')
            ->join('__DORMITORY_BUILDING__ d', 'd.number = a.building_number and d.garden_number = a.garden_number')
            ->where('a.status', DormitoryDorm::NORMAL)
            ->field('a.id,a.garden_number,c.name as garden_name,a.building_number,d.name as building_name,a.number,a.total_score,a.bed_count,a.bed_used_count')
            ->order('total_score', 'desc')
            ->paginate($list_rows);

        if ($results) {
            if (!is_array($results)) $results = $results->toArray();

            if (isset($results['data'])) {

                // 第一个是分数最大的
                $max = current($results['data']);

                // 获取比当前最大分分数高的人数
                $count = DormitoryDorm::where('total_score', '>', $max['total_score'])->count();

                foreach ($results['data'] as $key => $value) {
                    //数组中第一个是当前分数最高的
                    if ($key == 0) {
                        $results['data'][$key]['sort'] = $count + $key + 1;
                    } else {
                        // 继续循环
                        // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                        if ($results['data'][$key - 1]['total_score'] == $value['total_score']) {
                            $results['data'][$key]['sort'] = $results['data'][$key - 1]['sort'];
                        } else {
                            // 如果不等 那就看看有没有分页情况
                            // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                            $results['data'][$key]['sort'] = ($results['current_page'] - 1) * $list_rows + $key + 1;
                        }
                    }
                }
            }
        }

        $this->success('', $results);
    }

    /**
     * @ApiTitle    (我的宿舍排行)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/9/2 10:28)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/myDormRanking)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1567392702",
    "data": {
    "sort": 1
    }
    })
     */
    public function myDormRanking()
    {
        if (\app\common\model\User::STUDENT == $this->auth->target_type) {

            $bed = DormitoryDormBed::where('student_id', $this->auth->target_id)->find();
            if (!$bed) $this->success('', null);

            $dorm = DormitoryDorm::where('number', $bed['dorm_number'])->where('garden_number', $bed['garden_number'])->where('building_number', $bed['building_number'])->find();
            if (!$dorm) $this->success('', null);

            $count = DormitoryDorm::where('total_score', '>', $dorm['total_score'])->count();

            $this->success('', [
                'id' => $dorm['id'],
                'sort' => $count + 1,
                'bed_count' => $dorm['bed_count'],
                'bed_used_count' => $dorm['bed_used_count'],
                'total_score' => $dorm['total_score'],
            ]);
        }

        $this->success('', null);
    }

    /**
     * @ApiTitle    (寝室点评记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/12 15:07)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/record)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="dorm_id", type="int", required=true, description="寝室id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function record()
    {
        $dorm_id = $this->request->post('dorm_id');

        $dorm = DormitoryDorm::get($dorm_id);

        if (!$dorm)
            $this->error('寝室不存在');

        $data['list'] = BehaviorRecord::alias('a')
            ->join('__BEHAVIOR_RECORD_DETAIL__ b', 'b.record_id = a.id', 'right')
            ->where('a.garden_number', $dorm['garden_number'])
            ->where('a.building_number', $dorm['building_number'])
            ->where('a.dorm_number', $dorm['number'])
            ->where('a.student_id', 0)
            ->field('b.id,a.record_user_id,a.record_user_group,a.created_at,a.student_id,b.behavior_id,b.behavior_name,b.behavior_type,b.score')
            ->order('a.id', 'desc')
            ->paginate();

        $page = $this->request->request('page');

        if ($page < 2) {
            $data['images'] = BehaviorRecord::alias('a')
                ->join('__BEHAVIOR_RECORD_IMAGE__ b', 'b.record_id = a.id', 'right')
                ->where('a.garden_number', $dorm['garden_number'])
                ->where('a.building_number', $dorm['building_number'])
                ->where('a.dorm_number', $dorm['number'])
                ->where('a.student_id', 0)
                ->field('b.id,b.url')
                ->order('b.id', 'desc')
                ->limit(5)
                ->select();
        }

        $this->success('', $data);

    }

    /**
     * @ApiTitle    (获取寝室小程序码)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/13 11:49)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/qrcode)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="dorm_id", type="int", required=true, description="寝室id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function qrcode()
    {
        $dorm_id = $this->request->request('dorm_id');

        $dorm = DormitoryDorm::get($dorm_id);

        if (!$dorm)
            $this->error('寝室不存在');

        if ($dorm['qrcode']) {
            $this->success('', ['qrcode' => $dorm['qrcode']]);
        }

        $qrcode = DormitoryDorm::generateQrcode($dorm['id']);

        if ($qrcode) {
            $dorm->qrcode = $qrcode;
            $dorm->save();
            $this->success('', ['qrcode' => $qrcode]);
        }

        $this->error('获取二维码失败');

        /*$options = [
            'app_id'   => 'wx37aeea2bd44c69a3',
            'secret'   => 'f91f0737ff370e4ed7078b5a93241764',
            'token'    => '',
            'aes_key'  => ''
        ];

        $app = new Application($options);
        $accessToken = $app->access_token;
        $token = $accessToken->getToken(true);

        $params = [
            'scene' => $dorm['id'],
            'page'  => '',
            'width' => 600,
            'auto_color' => false,
            'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
        ];

        $code = getWXACodeUnlimit($token, $params);


        $public_path = ROOT_PATH . 'public';
        $uploads_path ='/uploads/' . date('Ymd', time()) . "/";

        if (!file_exists($public_path . $uploads_path)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($public_path . $uploads_path, 0777,true);
        }
        $filename = uniqid() . ".png";
        $new_file = $public_path . $uploads_path . $filename;

        $flag = file_put_contents($new_file, $code);

        if (!$flag) {
            $this->error('生成失败');
        }


        $dorm->qrcode = $uploads_path . $filename;
        $dorm->save();

        $this->success('', ['qrcode' => $uploads_path . $filename]);*/


        /*$app = new Application($options);
        $miniProgram = $app->mini_program;
        $result = $miniProgram->qrcode->getAppCodeUnlimit(json_encode(['dorm_id' => $dorm['id']]));*/

    }

    /**
     * @ApiTitle    (联动搜索 楼层列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/27 09:31)
     * @ApiSummary  ()
     * @ApiBody     ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/floors)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="building_id", type="int", required=true, description="楼栋id", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function floors()
    {
        $building_id = $this->request->request('building_id');
        $result = DormitoryBuilding::alias('building')
            ->join('__DORMITORY_DORM__ dorm', 'building.number = dorm.building_number and building.garden_number = dorm.garden_number')
            ->where('building.id', $building_id)
            ->where('dorm.status', DormitoryDorm::NORMAL)
            ->field('dorm.floor')
            ->group('dorm.floor')
            ->select();

        $data = [];
        foreach ($result as $key => $value) {
            $data[] = [
                'id' => $value['floor'],
                'name' => $value['floor'] . '层'
            ];
        }
        $this->success('', $data);
    }

    /**
     * @ApiTitle    (联动搜索 寝室列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDateTime (2019/8/27 09:31)
     * @ApiSummary  ()
     * @ApiBody     ()
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/dorm/cxSelect)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="building_id", type="int", required=true, description="楼栋id", sample="")
     * @ApiParams   (name="floor", type="int", required=false, description="楼层 ", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function cxSelect()
    {
        $building_id = $this->request->request('building_id');
        $floor = $this->request->request('floor', 0);
        $gender = $this->auth->gender;

        $result = DormitoryBuilding::alias('building')
            ->join('__DORMITORY_DORM__ dorm', 'building.number = dorm.building_number and building.garden_number = dorm.garden_number')
            ->where(function ($query) use ($building_id, $floor) {
                $query->where('building.id', $building_id);
                if ($floor) {
                    $query->where('dorm.floor', $floor);
                }
            })
            ->where('dorm.type', $gender)
            ->where('dorm.status', DormitoryDorm::NORMAL)
            ->field('dorm.id,dorm.number,dorm.name')
            ->select();

        $this->success('', $result);
    }

}
